package com.ddfeiyu.client.handler;


import com.alibaba.fastjson.JSON;
import com.ddfeiyu.agreement.log.LogRequest;
import com.ddfeiyu.agreement.log.LogResponse;
import com.ddfeiyu.client.MyBizHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LogHandler extends MyBizHandler<LogResponse> {

    private Logger logger = LoggerFactory.getLogger(LogHandler.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String channelId = ctx.channel().id().toString();
        logger.info("NettyClient--LogHandler--channelActive--channelId:[ {} ] ", channelId );

        ctx.writeAndFlush(new LogRequest("第一个traceId","第一个netty日志"));
        super.channelActive(ctx);
    }


    @Override
    protected void channelRead(Channel channel, LogResponse msg) throws Exception {
        String channelId = channel.id().toString();

        logger.info("NettyClient--LogHandler--channelId:[ {} ],消息内容：[ {} ]", channelId, JSON.toJSONString(msg));
        if (!msg.isSuccess()) {
            logger.error("NettyClient--LogHandler--channelId:[ {} ],失败[ {} ]",channelId);
            return;
        }
        logger.info("NettyClient--LogHandler--channelId:[ {} ],成功[ {} ]",channelId);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        String channelId = ctx.channel().id().toString();
        logger.error("NettyClient--LogHandler-exceptionCaught异常---channelId:[ {} ] ", channelId, cause);
        super.exceptionCaught(ctx, cause);
    }
}
